#clean up
rm(list=ls())

#load required libraries
library(spdep) 
library(maps)
library(rgdal)
library(MASS)
library(mvtnorm)
library(car)
library(readxl)
library(survival)
library(xtable)

#options
options(scipen=15)

#load data
creekYoder<-read_excel("creekYoder2.xlsx")
summary(creekYoder)
dim(creekYoder)
table(creekYoder$mou)
names(creekYoder)

###CREEK & YODER MODEL###
mod.cy<-clogit(mou~republicangovernor+unifiedrlege+citizenideology+oflocalitieswithmoa+I(percentcontiguousnew*100)+border+hispanicchange+totalcrimerate+stateunemployment+stateEdEffortScale+statehandhEffortScale+statepandcEffortScale+statepwEffortScale+strata(duration),method="breslow",data=creekYoder);summary(mod.cy);exp(mod.cy$coef)

###Export 2009 Creek and Yoder Data###
table(creekYoder$fips[creekYoder$year==2008]==creekYoder$fips[creekYoder$year==2009])
creekYoder$citizenideology[creekYoder$year==2009]<-creekYoder$citizenideology[creekYoder$year==2008]
cy.2009<-subset(creekYoder,year==2009)
cy.2009$unifiedrlege[cy.2009$unifiedrlege=="."]<-1
cy.2009$unifiedrlege<-as.numeric(cy.2009$unifiedrlege)

###Combine 2009 Creek and Yoder Data with Pooled Law Enforcement###
new.policy<-read.csv("policyArea.csv")
new.policy$fips<-recode(new.policy$ID,
"1=1;2=2;3=4;4=5;5=6;6=8;7=9;8=10;9=12;10=13;11=15;12=16;13=17;14=18;15=19;16=20;17=21;18=22;19=23;20=24;21=25;22=26;23=27;24=28;25=29;26=30;27=31;28=32;29=33;30=34;31=35;32=36;33=37;34=38;35=39;36=40;37=41;38=42;39=44;40=45;41=46;42=47;43=48;44=49;45=50;46=51;47=53;48=54;49=55;50=56")
new.law<-subset(new.policy,select=c(fips,score,demUnif,repUnif),subset=policy=="law")
cy.2009<-merge(x=cy.2009,y=new.law,by="fips")

###Estimate Effect of Creek and Yoder Predictors on Updated Dependent Variable###
###Ideology is 2008.
new.mod<-lm(score~republicangovernor+unifiedrlege+citizenideology+border+hispanicchange+totalcrimerate+stateunemployment+stateEdEffortScale+statehandhEffortScale+statepandcEffortScale+statepwEffortScale,data=cy.2009)
summary(new.mod)
print(xtable(new.mod),type="HTML",digits=4)
